<template>
  <div class="login-container">
    <h1 class="title">西藏自治区发展和改革委员会<br/>智慧党建办公系统</h1>
    <Form ref="loginForm" :model="form" inline :rules="ruleValidate">
      <FormItem prop="username">
        <Input v-model="form.username" prefix="md-person" placeholder="账号" />
      </FormItem>
      <FormItem prop="password">
        <Input type="password" v-model="form.password" prefix="md-lock" password placeholder="密码" />
      </FormItem>
      <FormItem prop="verCode" class="verCode-item">
        <Input class="verCode" v-model="form.verCode" placeholder="验证码" />
        <img class="rand-pic" @click="changeVerCode" :src="verCodeUrl" alt="">
      </FormItem>
    </Form>
    <div class="login-btns">
      <Button class="login-btn" size="large" type="primary" long @click="handleSubmit('loginForm')">
        登 录
      </Button>
    </div>
    <system-footer />
  </div>
</template>

<script>
import SystemFooter from '@/components/SystemFooter';
import { getCaptchaRest, loginRest } from '@/common/apis/system'
import { randomString } from '@/common/utils'

export default {
  name: "login",
  components: {
    SystemFooter
  },
  data() {
    return {
      verCodeUrl: '',
      form: {
        username: '',
        password: '',
        verCode: ''
      },
      ruleValidate: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        verCode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.changeVerCode()
  },
  methods: {
    changeVerCode() {
      this.randStr = randomString()
      const params = { randomStr: this.randStr }
      getCaptchaRest(params).then(result => {
        const blob = new Blob([result.data], { type: 'image/jpeg' })
        this.verCodeUrl = window.URL.createObjectURL(blob)
        this.form.verCode = ''
      })
    },
    handleSubmit (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          const { username, password, verCode } = this.form
          const params = {
            loginName: username,
            password,
            verCode,
            randomStr: this.randStr
          }
          loginRest(params).then(result => {
            if(result.data.code === 200) {
              this.$store.commit('SET_TOKEN', result.data.content.accessToken)
              this.$store.commit('SET_USERINFO', result.data.content.user)
              this.$router.push('/')
            } else if (result.data.msg === '验证码不正确'){
              this.form.verCode = ''
            }
          })
        }
      })
    }
  }
}
</script>
